package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Autowired
    private ApUserMapper apUserMapper;

    /*
     * TODO 根据状态查询实名认证列表
     *  */
    @Override
    public ResponseResult queueListStatus(AuthDTO authDTO) {
        //TODO 1. 检查参数
        authDTO.checkParam();
        //TODO 2. 封装查询条件
        // 2.1  分页条件
        IPage<ApUserRealname> pageRes = new Page<>(authDTO.getPage(),authDTO.getSize());
        //todo 2.2  status
        LambdaQueryWrapper<ApUserRealname> lambdaQuery = Wrappers.lambdaQuery();
        //TODO 如果status不为空 按照状态查询
        if (authDTO.getStatus()!=null){
            lambdaQuery.eq(ApUserRealname::getStatus,authDTO.getStatus());
        }
        //TODO 3. 执行条件分页查询
        IPage<ApUserRealname> pageResult = this.page(pageRes,lambdaQuery);
        //TODO 4. 封装结果
         return new PageResponseResult(authDTO.getPage(), authDTO.getSize(), pageResult.getTotal(), pageResult.getRecords());

    }


    /*
    * TODO 用户认证审核
    *  */
    //todo 开启全局事务
    @GlobalTransactional(rollbackFor = Exception.class,timeoutMills = 100000)
    @Override
    public ResponseResult updateStatusById(AuthDTO authDTO, Short status) {
        //TODO 检查参数
        // 1.1 检查id
        if (authDTO==null||authDTO.getId()==null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"实名认证参数不能为空");
        }

        //todo 1.2 根据id 查询实名认证信息
        ApUserRealname userRealname = getById(authDTO.getId());

        //todo  1.3 检查状态  1待审核 2失败 9通过
        if (!userRealname.getStatus().equals(AdminConstants.WAIT_AUTH)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"实名认证状态错误");
        }
        //todo 1.4 查询关联的apUser信息
        ApUser apUser = apUserMapper.selectById(userRealname.getUserId());
        if (apUser==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证关联的app用户信息不存在");
        }
        //TODO 2. 修改实名认证的状态
        userRealname.setStatus(status);

        if (StringUtils.isNotBlank(authDTO.getMsg())){
            //设置驳回原因
            userRealname.setReason(authDTO.getMsg());
        }
        updateById(userRealname);
        //TODO 3. 判断是否为通过 状态: 9
        if (AdminConstants.PASS_AUTH.equals(userRealname.getStatus())){
            //TODO 3.1  远程开通自媒体账户
            WmUser wmUser = createWmUser(apUser);

            //TODO 3.2  创建作者信息  // ap_user   wm_user
            createAuthor(wmUser,apUser);
        }

        return ResponseResult.okResult();
    }


    @Autowired
    private ArticleFeign articleFeign;
    /*
    * todo 创建作者信息
    *  */
    private  void createAuthor(WmUser wmUser, ApUser apUser) {
        //todo 远程查询作者信息是否存在
        ResponseResult<ApAuthor> authorResult = articleFeign.findByUserId(apUser.getId());
        if (authorResult.getCode().intValue()!=0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,authorResult.getErrorMessage());
        }
        ApAuthor author=authorResult.getData();
        if (author!=null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"对应的作者已经存在");
        }
        //TODO 添加作者信息
        author=new ApAuthor();
        author.setName(apUser.getName());
        author.setType(2);    //自媒体人类型：  1 签约合作商 2 平台自媒体人
        author.setUserId(apUser.getId()); //todo 设置社交账号id
        author.setWmUserId(wmUser.getId());//设置自媒体账号id
        author.setCreatedTime(new Date());
        //todo 保存作者信息
        ResponseResult saveResult = articleFeign.save(author);

        //todo 如果信息不存在
        if (saveResult.getCode().intValue()!=0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,saveResult.getErrorMessage());
        }
    }

    @Autowired
    private WemediaFeign wemediaFeign;

    /*
    * todo 创建自媒体账户
    *  */
    private WmUser createWmUser(ApUser apUser) {
        // 1. 查询关联自媒体账户是否已经创建
        ResponseResult<WmUser> wmUserResult = wemediaFeign.queueUserByName(apUser.getName());
        if (wmUserResult.getCode().intValue() != 0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,wmUserResult.getErrorMessage());
        }
        WmUser wmUser = wmUserResult.getData();
        if(wmUser!=null){ // 自媒体账户已经有了
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"对应的自媒体账户已经存在");
        }
        wmUser = new WmUser(); // 创建自媒体账户
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(9); // 正常
        wmUser.setType(0); //个人
        wmUser.setCreatedTime(new Date());

        ResponseResult<WmUser> saveResult = wemediaFeign.saveVmUser(wmUser);
        if (saveResult.getCode().intValue()!=0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,saveResult.getErrorMessage());
        }
        // 2. 创建自媒体账户
        return saveResult.getData();// 已经设置了id的wmUser对象
    }
}
